package edu.suda.cxtz.controller;

import edu.suda.cxtz.entity.Job;
import edu.suda.cxtz.entity.User;
import edu.suda.cxtz.entity.dto.JobDto;
import edu.suda.cxtz.entity.dto.JobQueryCriteria;
import edu.suda.cxtz.service.JobService;
import edu.suda.cxtz.modules.exception.BadRequestException;
import edu.suda.cxtz.utils.PageResult;
import edu.suda.cxtz.utils.SecurityUtils;
import lombok.RequiredArgsConstructor;
import org.springframework.data.domain.Pageable;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.Set;

@RestController
@RequiredArgsConstructor
@RequestMapping("/api/job")
public class JobController {

    private final JobService jobService;
    private static final String ENTITY_NAME = "job";

    @GetMapping("/query")
    @PreAuthorize("@el.check('job:list','user:list')")
    public ResponseEntity<PageResult<JobDto>> queryJob(JobQueryCriteria criteria, Pageable pageable){
        return new ResponseEntity<>(jobService.queryAll(criteria, pageable), HttpStatus.OK);
    }

//    @Log("新增岗位")
    @PostMapping
    @PreAuthorize("@el.check('job:add')")
    public ResponseEntity<Object> createJob(@Validated @RequestBody Job resources){
        String user = SecurityUtils.getCurrentUsername();
        if (resources.getId() != null) {
            throw new BadRequestException("A new "+ ENTITY_NAME +" cannot already have an ID");
        }
        resources.setCreateBy(user);
        jobService.create(resources);
        return new ResponseEntity<>(HttpStatus.CREATED);
    }

//    @Log("修改岗位")
    @PutMapping
    @PreAuthorize("@el.check('job:edit')")
    public ResponseEntity<Object> updateJob(@Validated(Job.Update.class) @RequestBody Job resources){
        jobService.update(resources);
        return new ResponseEntity<>(HttpStatus.NO_CONTENT);
    }

//    @Log("删除岗位")
    @DeleteMapping
    @PreAuthorize("@el.check('job:del')")
    public ResponseEntity<Object> deleteJob(@RequestBody Set<Long> ids){
        // 验证是否被用户关联
        jobService.verification(ids);
        jobService.delete(ids);
        return new ResponseEntity<>(HttpStatus.OK);
    }
}
